import { defineStore } from "pinia";
import piniaPersistConfig from "@/config/piniaPersist";
import { User } from "@/api/interface";
import axios from "axios";

const baseUrl = import.meta.env.VITE_BASE_URL;

export const useUserStore = defineStore("user", {
  state: () => ({
    token: "",
    userInfo: {} as User.ResUser,
    userList: [] as any[] // 新增 userList
  }),
  actions: {
    async fetchUserList() {
      const response = await axios.get(baseUrl + "/api/carbon/getAllUsers");
      if (response.data && response.data.code === 200) {
        console.log("User list fetched successfully:", response.data.data);
        this.userList = response.data.data || [];
      } else {
        this.userList = [];
      }
    },
    async login(username: string, password: string) {
      // 确保 userList 已经有数据
      await this.fetchUserList();
      const user = this.userList.find(user => user.userName === username && user.password === password);
      if (user) {
        this.setToken("dummy-token"); // 生成一个假的 token
        this.setUserInfo(user);
        return true;
      } else {
        return false;
      }
    },
    logout() {
      this.setToken("");
      this.setUserInfo({} as User.ResUser);
    },
    loadUserFromLocalStorage() {
      const token = localStorage.getItem("token");
      const userInfo = localStorage.getItem("userInfo");
      if (token && userInfo) {
        this.setToken(token);
        this.setUserInfo(JSON.parse(userInfo));
      }
    },
    setToken(token: string) {
      this.token = token;
      localStorage.setItem("token", token);
    },
    setUserInfo(userInfo: any) {
      this.userInfo = userInfo;
      localStorage.setItem("userInfo", JSON.stringify(userInfo));
    }
  },
  persist: piniaPersistConfig("user")
});